package com.shuaigexue.aicodegenerate.service;


import cn.hutool.core.util.StrUtil;
import com.shuaigexue.aicodegenerate.response.RandomImageResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class RandomImageService {
    
    private static final String API_URL = "https://api.btstu.cn/sjbz/api.php";
    private final RestTemplate restTemplate;
    
    public RandomImageService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
    
    public String getRandomImageUrl(String category, String device) {
        try {
            Map<String, String> params = new HashMap<>();
            params.put("format", "json");
            
            if (StrUtil.isNotBlank(category)) {
                params.put("lx", category);
            }
            
            if (StrUtil.isNotBlank(device)) {
                params.put("method", device);
            }
            
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(API_URL);
            params.forEach(builder::queryParam);
            URI requestUrl = builder.build().toUri();
            
            HttpHeaders headers = new HttpHeaders();
            headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
            
            HttpEntity<Void> requestEntity = new HttpEntity<>(headers);
            
            ResponseEntity<RandomImageResponse> response = restTemplate.exchange(
                requestUrl,
                HttpMethod.GET,
                requestEntity,
                RandomImageResponse.class
            );
            
            if (response.getBody() != null && response.getBody().isSuccess()) {
                return response.getBody().getImgUrl();
            }
            
            log.error("随机图片API返回错误: {}", response.getBody());
            return null;
            
        } catch (Exception e) {
            log.error("调用随机图片API失败", e);
            return null;
        }
    }
    
    public String getRandomImageUrl() {
        return getRandomImageUrl("dongman", "pc");
    }
}